﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using WisDom.SmartTMS.Data;
using WisDom.SmartTMS.Dtos;
using WisDom.SmartTMS.Entities;
using WisDom.SmartTMS.Enums;
using WisDom.SmartTMS.Interface;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Services;
using Volo.Abp.ObjectMapping;
using Microsoft.AspNetCore.Mvc;

namespace WisDom.SmartTMS.Service
{
    public class CarriageService :SmartTMSAppService, ICarriageService
    {
        //依赖注入
        private readonly IRepository<Contract_Carriage, Guid> _irepository;
        private readonly IBusinessAuditRepository _businessAudit;//审核仓储

        public CarriageService(IRepository<Contract_Carriage, Guid> irepository, IBusinessAuditRepository businessAudit)
        {
            _irepository = irepository;
            _businessAudit = businessAudit;
        }

        /// <summary>
        /// 转批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public Task AuditAsync([FromForm]AuditDto input)
        {
            try
            {
                //拿到审批主记录
                BusinessAudit auditInfo = _businessAudit.GetAuditById(input.AuditId, BusinessType.Carriage).SingleOrDefault();
                string a = "39ff0018-7f5a-6039-2e7a-1bf4c4787611";
                Guid b = new Guid(a);
                //当前审核人处理审批
                auditInfo.ProcessAudit(b, "smart", input.Remark, AuditState.InAudit);

                //持久化（更新主信息）
                _businessAudit.UpdateAsync(auditInfo);

                //新增下一个人审批日志
                auditInfo.AddAuditLogs(GuidGenerator.Create(), GuidGenerator.Create(), input.CreatorRealName, input.State);


                return UnitOfWorkManager.Current.SaveChangesAsync();  //完成工作单元
            }
            catch (Exception ex)
            {

                throw ex;
            }
            
    }

        /// <summary>
        /// 终止审批（可能是审核通过或不通过）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public Task EndAuditAsync([FromForm]AuditDto input)
        {
            try
            {
                BusinessAudit businessAudit = _businessAudit.GetAuditById(input.AuditId, BusinessType.Carriage).SingleOrDefault();
                string a = "39ff0018-7f5a-6039-2e7a-1bf4c4787611";
                Guid b = new Guid(a);
                //终止审批(input.State为通过或拒绝）
                businessAudit.EndAudit(b, "smart", input.State, input.Remark);
                //持久化
                _businessAudit.UpdateAsync(businessAudit);
                return UnitOfWorkManager.Current.SaveChangesAsync();  //完成工作单元
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 查看审核记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<CarriageAuditDto>> GetShipperAuditAsync(PagedAndSortedResultRequestDto input)
        {
            try
            {
                var query = from s in _irepository
                            join b in _businessAudit.GetAuditList(BusinessType.Carriage) on s.Id equals b.BusinessCode
                            orderby s.Id
                            select new CarriageAuditDto
                            {
                                Id = b.Id,
                                CreateTime = DateTime.Now,
                                CreatorId = s.Id,
                                Deleted = s.Deleted,
                                ContractNum = s.ContractNum,
                                ContractTitle = s.ContractTitle,
                                CarriageUnit = s.CarriageUnit,
                                CarriageMan = s.CarriageMan,
                                Line = s.Line,
                                FreightRates = s.FreightRates,
                                CharterConditionTonnage = s.CharterConditionTonnage,
                                CharterValue = s.CharterValue,
                                SignedTime = s.SignedTime,
                                Operator = s.Operator,
                                ContractMoney = s.ContractMoney,
                                ProjectDescription = s.ProjectDescription,
                                MainClause = s.MainClause,
                                Accessory = s.Accessory,
                                Approver = s.Approver,
                                BusinessCode = b.BusinessCode,
                                BusinessTypeCode = b.BusinessTypeCode,
                                State = b.State,
                                AuditTime = DateTime.Now,
                                CreatorRealName = b.CreatorRealName,
                                Remark = s.Remark
                            };
                //获取总条数
                var totalCount = await query.CountAsync();

                //从仓储获取实体数据对象
                List<CarriageAuditDto> vehicleAudits = await query.Skip(input.SkipCount).Take(input.MaxResultCount).ToListAsync();

                //返回分页结果集
                return new PagedResultDto<CarriageAuditDto>(totalCount, vehicleAudits);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 在审核日志表根据ID查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Task<CarriageAuditDto> GetCarriageAuditByIdAsync(Guid id)
        {
            try
            {
                //车辆表和审核表联查
                var query = from v in _irepository   //车辆信息
                            join a in _businessAudit.GetAuditById(id, BusinessType.Carriage) //单个车辆审核信息
                            on v.Id equals a.BusinessCode     //连接条件
                            select new CarriageAuditDto
                            {
                                Id = a.Id,
                                CreateTime = DateTime.Now,
                                CreatorId = v.Id,
                                Deleted = v.Deleted,
                                ContractNum = v.ContractNum,
                                ContractTitle = v.ContractTitle,
                                CarriageUnit = v.CarriageUnit,
                                CarriageMan = v.CarriageMan,
                                Line = v.Line,
                                FreightRates = v.FreightRates,
                                CharterConditionTonnage = v.CharterConditionTonnage,
                                CharterValue = v.CharterValue,
                                SignedTime = v.SignedTime,
                                Operator = v.Operator,
                                ContractMoney = v.ContractMoney,
                                ProjectDescription = v.ProjectDescription,
                                MainClause = v.MainClause,
                                Accessory = v.Accessory,
                                Approver = v.Approver,
                                BusinessCode = a.BusinessCode,
                                BusinessTypeCode = a.BusinessTypeCode,
                                State = a.State,
                                AuditTime = DateTime.Now,
                                CreatorRealName = a.CreatorRealName,
                                Remark = v.Remark
                                //auidtLogsDtos = ObjectMapper.Map<List<BusinessAuditLogs>, List<AuidtLogsDto>>(a.BusinessAuditLogs)
                            };

                return query.SingleOrDefaultAsync();  //返回
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}
